<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Validator;

use Admin\Entity\SelfLocationMember;
use Laminas\I18n\Translator\Translator;
use Laminas\Validator\AbstractValidator;

class LocationMemberExistsValidator extends AbstractValidator
{
    const NOT_SCALAR    = 'notScalar';
    const MEMBER_EXISTS = 'memberExists';

    protected $options = [
        'entityManager',
        'member'
    ];

    protected $messageTemplates = [];

    public function __construct($options = null)
    {
        if(is_array($options)) {
            if(isset($options['entityManager']))    $this->options['entityManager'] = $options['entityManager'];
            if(isset($options['member']))           $this->options['member']        = $options['member'];
        }

        $trans = new Translator();
        $this->messageTemplates = [
            self::NOT_SCALAR    => $trans->translate("这不是一个标准输入值"),
            self::MEMBER_EXISTS => $trans->translate("该登录账号已经存在")
        ];

        parent::__construct($options);
    }

    public function isValid($value)
    {
        if(!is_scalar($value)) {
            $this->error(self::NOT_SCALAR);
            return false;
        }

        $entityManager  = $this->options['entityManager'];
        $member         = $entityManager->getRepository(SelfLocationMember::class)->findOneByMemberAccount($value);

        if($this->options['member'] == null) {
            $isValid = ($member==null);
        } else {
            if($this->options['member']->getMemberAccount() != $value && $member != null)
                $isValid = false;
            else
                $isValid = true;
        }

        if(!$isValid) $this->error(self::MEMBER_EXISTS);

        return $isValid;
    }
}